package com.heima.homeservicemanagementsystem.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.homeservicemanagementsystem.config.GithubConstants;
import com.heima.homeservicemanagementsystem.entity.GithubInfo;
import com.heima.homeservicemanagementsystem.entity.SysUser;
import com.heima.homeservicemanagementsystem.entity.bo.AccessToken;
import com.heima.homeservicemanagementsystem.entity.giteeInfo;
import com.heima.homeservicemanagementsystem.module.Result;
import com.heima.homeservicemanagementsystem.openfeign.GithubClient;
import com.heima.homeservicemanagementsystem.openfeign.GithubOauthClient;
import com.heima.homeservicemanagementsystem.service.GithubLoginService;
import com.heima.homeservicemanagementsystem.service.SysUserService;
import com.heima.homeservicemanagementsystem.utils.RedisClient;
import feign.FeignException;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

import static cn.dev33.satoken.SaManager.log;

/**
 * @Description
 * @Author jcf
 * @Date 2025/3/10
 */
@Service
public class GithubLoginServiceImpl implements GithubLoginService {
    private static final Logger log = LoggerFactory.getLogger(GithubLoginServiceImpl.class);
    @Autowired
    private GithubConstants githubConstants;
    @Resource
    private SysUserService sysUserService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private GithubClient githubClient;
    @Autowired
    private GithubOauthClient githubOauthClient;
    @Override
    public Result getGithubAuth() {
        // 授权地址 ,进行Encode转码
        String authorizeURL = githubConstants.getAuthorizeURL();

        // 回调地址 ,回调地址要进行Encode转码
        String redirectUri = githubConstants.getRedirectURI();

        //用于第三方应用防止CSRF攻击
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        // https://github.com/login/oauth/authorize
        // ?client_id=appid
        // &redirect_uri=redirectUri
        // &state=afasd

        // 拼接url
        StringBuilder url = new StringBuilder();
        url.append(authorizeURL);
        url.append("?client_id=" + githubConstants.getAppID());
        // 转码
        url.append("&redirect_uri=" + githubConstants.getRedirectURI());
        url.append("&state=" + uuid);
        return Result.success("操作成功", url);
    }

    @Override
    public Result githubAccessToken(String code) {
        try {
            // 调用 Feign 客户端获取 GitHub 访问令牌
            String accessTokenResponse = githubOauthClient.getAccessToken(
                    githubConstants.getAppID(),
                    githubConstants.getAppKEY(),
                    code,
                    githubConstants.getRedirectURI()
            );

            // 返回成功结果
            return Result.success("认证成功", accessTokenResponse);

        } catch (FeignException e) {
            // 处理 GitHub API 返回的错误（如 401 Unauthorized）
            log.error("认证失败: {}", e.getMessage());
            return Result.error("认证失败: " + e.getMessage());
        } catch (Exception e) {
            // 处理其他错误
            log.error("发生错误: {}", e.getMessage());
            return Result.error("发生错误: " + e.getMessage());
        }
//        // 构造访问令牌的请求 URL
//        String url = "https://github.com/login/oauth/access_token";  // GitHub token 请求的 URL
////        log.info("重定向地址：{}", githubConstants.getRedirectURI());
//
//// 设置请求体，传递参数
//        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
//        body.add("client_id", githubConstants.getAppID());
//        body.add("client_secret", githubConstants.getAppKEY());
//        body.add("code", code);
//        body.add("redirect_uri", githubConstants.getRedirectURI());
//
//// 设置请求头，确保是以 application/x-www-form-urlencoded 格式发送请求
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//
//// 构造HttpEntity，包括请求头和请求体
//        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(body, headers);
//
//        try {
//            // 发送 POST 请求
//            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
//
//            // 返回结果，假设认证成功
//            return Result.success("认证成功", exchange.getBody());
//
//        } catch (HttpClientErrorException e) {
//            // 处理 401 Unauthorized 错误
//            log.error("认证失败: {}", e.getMessage());
//            return Result.error("认证失败: " + e.getMessage());
//        } catch (Exception e) {
//            // 处理其他错误
//            log.error("发生错误: {}", e.getMessage());
//            return Result.error("发生错误: " + e.getMessage());
//        }

    }

    @Override
    public Result githubLogin(GithubInfo githubUserInfo) {
        SysUser user = sysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getGithubLogin, githubUserInfo.getLogin()));

        if (Objects.isNull(user)) {
            log.info("用户信息：{}", user);
            return Result.error("登录失败，请重新验证并查看是否绑定gitee");
        } else {
            StpUtil.login(user.getId(), "pc");
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            Map<String, String> map = new HashMap<>(2);
            map.put("tokenHead", tokenInfo.tokenName);
            map.put("token", tokenInfo.tokenValue);
            return Result.success(map);
        }
    }

    @Override
    public GithubInfo getGithubUserInfo(String accessToken) throws JsonProcessingException {
        log.info("用户的accesstoken：{}", accessToken);
        GithubInfo user = githubClient.getUser("token " + accessToken);
        log.info("用户信息：{}", user);
//        String url = githubConstants.getUserInfo();
//        HttpHeaders headers = new HttpHeaders();
//        headers.set("Authorization", "token " + accessToken);
//        HttpEntity<String> entity = new HttpEntity<>(headers);
//
//        // 发送 GET 请求
//        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
//        // 判断是否请求成功
////        if (exchange.getStatusCode().is2xxSuccessful()) {
////            return Result.success(exchange.getBody());
////        }
//        //返回的是json数据
//        String responseBody = exchange.getBody();
//        ObjectMapper objectMapper = new ObjectMapper();
//        GithubInfo githubInfo = objectMapper.readValue(responseBody, GithubInfo.class);
//        if (githubInfo == null) {
//            throw new RuntimeException("没有查询用户信息");
//        }
        return user;

    }
}
